<template>
   <view class="container">
      <scroll-view scroll-y="true" class="form-container">
         <!-- 图片上传 -->
         <view class="form-item">
            <text class="form-label">车位图片<text class="required">*</text></text>
            <view class="upload-container">
               <view class="image-preview" v-for="(item, index) in form.photoUrls" :key="index">
                  <image class="preview-image" :src="item" mode="aspectFill"></image>
                  <view class="delete-btn" @click="deleteImage(index)">
                     <!-- <text class="iconfont icon-close"></text> -->
                     <icon type="clear" size="16"/>
                  </view>
               </view>
               <view class="upload-btn" @click="chooseImage" v-if="form.photoUrls.length < 3">
                  <text class="iconfont icon-add"></text>
                  <text class="upload-text">上传图片</text>
                  <text class="upload-tip">(最多3张)</text>
               </view>
            </view>
         </view>

         <!-- 表单内容 -->
         <view class="form-item">
            <text class="form-label">标题<text class="required">*</text></text>
            <input class="form-input" v-model="form.title" placeholder="请输入标题" />
         </view>

         <view class="form-item">
            <text class="form-label">描述<text class="required">*</text></text>
            <textarea class="form-textarea" v-model="form.description" placeholder="请输入详细描述"></textarea>
         </view>

         <view class="form-item">
            <text class="form-label">状态<text class="required">*</text></text>
            <picker @change="onStatusChange" :value="form.status" :range="statusOptions" range-key="dictLabel">
               <view class="picker">
                  {{ form.status || '请选择状态' }}
               </view>
            </picker>
         </view>

         <view class="form-item">
            <text class="form-label">最短租期(月)<text class="required">*</text></text>
            <input class="form-input" type="number" v-model="form.minRentalPeriod" placeholder="请输入最短租期" />
         </view>

         <view class="form-item">
            <text class="form-label">价格(元/月)<text class="required">*</text></text>
            <input class="form-input" type="number" v-model="form.pricePerMonth" placeholder="请输入价格" />
         </view>

         <view class="form-item">
            <text class="form-label">可充电</text>
            <picker @change="onChargingChange" :value="form.isEvCharging" :range="yesNoOptions" range-key="dictLabel">
               <view class="picker">
                  {{ yesNoOptions.find(item => item.dictValue == form.isEvCharging) ? yesNoOptions.find(item => item.dictValue == form.isEvCharging).dictLabel : '请选择' }}
               </view>
            </picker>
         </view>

         <view class="form-item">
            <text class="form-label">可议价</text>
            <picker @change="onBargainChange" :value="form.isNegotiable" :range="yesNoOptions" range-key="dictLabel">
               <view class="picker">
                  {{ yesNoOptions.find(item => item.dictValue == form.isNegotiable) ? yesNoOptions.find(item => item.dictValue == form.isNegotiable).dictLabel : '请选择' }}
               </view>
            </picker>
         </view>

         <view class="form-item">
            <text class="form-label">选择位置<text class="required">*</text></text>
            <view class="location-input">
               <input class="input" v-model="form.address" placeholder="请选择位置" disabled />
               <button class="location-btn" @click="chooseLocation">
                  <text class="iconfont icon-map-filling"></text>
               </button>
            </view>
         </view>

         <view class="form-item">
            <text class="form-label">车位编号</text>
            <input class="form-input" v-model="form.parkingNumber" placeholder="请输入车位编号" />
         </view>

         <view class="form-item">
            <text class="form-label">所在建筑</text>
            <input class="form-input" v-model="form.buildingName" placeholder="请输入所在建筑" />
         </view>

         <view class="form-item">
            <text class="form-label">楼层</text>
            <input class="form-input" v-model="form.floor" placeholder="请输入楼层" />
         </view>

         <!-- 提交按钮 -->
         <button class="submit-btn" type="primary" @click="submitForm">发布</button>
      </scroll-view>
   </view>
</template>

<script>
   import {
      listSpots,
      getSpots,
      delMineSpot
   } from "@/api/parking/spots";
   import {
      addMineSpot,
      updateMineSpot,
      uploadSpotImage
   } from "@/api/parking/spots";


   export default {
      data() {
         return {
            form: {
               parkingId: null,
               title: '',
               description: '',
               minRentalPeriod: '',
               pricePerMonth: '',
               isEvCharging: 'N',
               isNegotiable: 'N',
               status: '可租',
               address: '',
               parkingNumber: '',
               buildingName: '',
               floor: '',
               latitude: null,
               longitude: null,
               address: '',
               photoUrls: [],
            },
            statusOptions: [],
            yesNoOptions: [],
            markers: []
         }
      },
      created() {
         this.getDicts('parking_spot_status').then(res => {
            this.statusOptions = res.data;
         });
         this.getDicts('sys_yes_no').then(res => {
            this.yesNoOptions = res.data;
         });
      },
      onLoad(options) {
         if (options.id) {
            // 编辑
            this.form.parkingId = options.id;
            getSpots(options.id).then(res => {
               this.form = res.data
               // 确保photoUrls是数组
               if (this.form.photoUrls && typeof this.form.photoUrls === 'string') {
                  this.form.photoUrls = this.form.photoUrls.split(',');
               } else {
                  this.form.photoUrls = [];
               }
            });
         }
      },
      methods: {
         // 选择图片
         chooseImage() {
            uni.chooseImage({
               count: 3 - this.form.photoUrls.length, // 最多选择3张
               sizeType: ['compressed'], // 压缩图
               sourceType: ['album', 'camera'], // 相册和相机
               success: (res) => {
                  // 检查是否超过3张
                  const remaining = 3 - this.form.photoUrls.length;
                  if (res.tempFilePaths.length > remaining) {
                     uni.showToast({
                        title: `最多只能上传3张图片`,
                        icon: 'none'
                     });
                     return;
                  }

                  // 上传图片
                  uni.showLoading({
                     title: '上传中...'
                  });
                  const uploadTasks = res.tempFilePaths.map(filePath => {
                     return uploadSpotImage({
                        filePath: filePath
                     }).then(res => {
                        return res.data;
                     });
                  });

                  Promise.all(uploadTasks).then(urls => {
                     this.form.photoUrls = [...this.form.photoUrls, ...urls];
                     uni.hideLoading();
                  }).catch(err => {
                     console.error('上传失败:', err);
                     uni.hideLoading();
                     uni.showToast({
                        title: '上传失败',
                        icon: 'none'
                     });
                  });
               }
            });
         },

         // 删除图片
         deleteImage(index) {
            this.form.photoUrls.splice(index, 1);
         },

         // 充电开关变化
         onChargingChange(e) {
            this.form.isEvCharging = this.yesNoOptions[e.detail.value].dictValue;
         },

         // 议价开关变化
         onBargainChange(e) {
            this.form.isNegotiable = this.yesNoOptions[e.detail.value].dictValue;
         },

         // 选择位置
         chooseLocation() {
            uni.chooseLocation({
               success: (res) => {
                  this.form.latitude = res.latitude
                  this.form.longitude = res.longitude
                  this.form.address = res.address // 自动填充地址

                  // 更新地图标记
                  this.markers = [{
                     id: 1,
                     latitude: res.latitude,
                     longitude: res.longitude,
                     title: '车位位置'
                  }]
               },
               fail: (err) => {
                  console.error('选择位置失败:', err)
                  uni.showToast({
                     title: '选择位置失败',
                     icon: 'none'
                  })
               }
            })
         },

         // 验证表单
         validateForm() {
            if (!this.form.title) {
               uni.showToast({
                  title: '请输入标题',
                  icon: 'none'
               })
               return false
            }
            if (!this.form.description) {
               uni.showToast({
                  title: '请输入描述',
                  icon: 'none'
               })
               return false
            }
            if (!this.form.minRentalPeriod) {
               uni.showToast({
                  title: '请输入最短租期',
                  icon: 'none'
               })
               return false
            }
            if (!this.form.pricePerMonth) {
               uni.showToast({
                  title: '请输入价格',
                  icon: 'none'
               })
               return false
            }
            if (!this.form.address) {
               uni.showToast({
                  title: '请输入地址',
                  icon: 'none'
               })
               return false
            }
            if (this.form.photoUrls.length === 0) {
               uni.showToast({
                  title: '请至少上传一张图片',
                  icon: 'none'
               })
               return false
            }
            return true
         },

         // 提交表单
         submitForm() {
            if (!this.validateForm()) return

            uni.showLoading({
               title: '发布中...'
            })

            // 处理图片URL为字符串
            const formData = {
               ...this.form,
               photoUrls: this.form.photoUrls.join(',')
            };

            if (this.form.id) {
               updateMineSpot(formData).then(res => {
                  uni.hideLoading();
                  this.$modal.alert('发布成功');
                  this.$tab.switchTab('/pages/parking/spotlist/index');
               })
            } else {
               addMineSpot(formData).then(res => {
                  uni.hideLoading();
                  this.$modal.alert('发布成功');
                  this.$tab.switchTab('/pages/parking/spotlist/index');
               })
            }
         },

         // 重置表单
         resetForm() {
            this.form = {
               parkingId: null,
               title: '',
               description: '',
               minRentalPeriod: '',
               pricePerMonth: '',
               isEvCharging: false,
               isNegotiable: false,
               address: '',
               parkingNumber: '',
               buildingName: '',
               floor: '',
               latitude: null,
               longitude: null,
               address: '',
               photoUrls: [],
            }
            this.markers = []
         },

         // 状态选择变化
         onStatusChange(e) {
            this.statusIndex = e.detail.value;
            this.form.status = this.statusOptions[this.statusIndex].dictValue;
         },
      }
   }
</script>

<style scoped>
   @import '@/static/iconfont/iconfont.css';

   .container {
      display: flex;
      flex-direction: column;
      height: 100vh;
      background-color: #f5f5f5;
   }

   .form-container {
      padding: 20rpx;
      height: 100%;
   }

   .form-title {
      font-size: 36rpx;
      font-weight: bold;
      text-align: center;
      margin: 20rpx 0 40rpx;
      color: #333;
   }

   .form-item {
      margin-bottom: 30rpx;
      background-color: #fff;
      padding: 20rpx;
      border-radius: 12rpx;
      box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
   }

   .form-label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 10rpx;
      display: block;
      position: relative;
   }

   .required {
      color: #ff4d4f;
      margin-left: 4rpx;
      font-size: 24rpx;
      position: relative;
      top: -2rpx;
   }

   .form-input {
      height: 80rpx;
      font-size: 28rpx;
      border: 1rpx solid #eee;
      border-radius: 8rpx;
      padding: 0 20rpx;
   }

   .form-textarea {
      width: 100%;
      height: 200rpx;
      font-size: 28rpx;
      border: 1rpx solid #eee;
      border-radius: 8rpx;
      padding: 20rpx;
      box-sizing: border-box;
   }

   .submit-btn {
      margin-top: 50rpx;
      background-color: #007aff;
      color: #fff;
      border-radius: 50rpx;
   }

   .picker {
      height: 80rpx;
      line-height: 80rpx;
      font-size: 28rpx;
      border: 1rpx solid #eee;
      border-radius: 8rpx;
      padding: 0 20rpx;
      color: #333;
   }

   .location-input {
      display: flex;
      align-items: center;
      gap: 20rpx;
   }

   .input {
      flex: 1;
      height: 88rpx;
      border: 2rpx solid #eee;
      border-radius: 12rpx;
      padding: 0 24rpx;
      font-size: 30rpx;
      background-color: #f8f8f8;
   }

   .location-btn {
      width: 88rpx;
      height: 88rpx;
      padding: 0;
      margin: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #007aff;
      border-radius: 12rpx;
   }

   .location-btn .iconfont {
      color: #fff;
      font-size: 40rpx;
   }

   /* 图片上传样式 */
   .upload-container {
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;
   }

   .image-preview {
      width: 200rpx;
      height: 200rpx;
      position: relative;
      border-radius: 8rpx;
      overflow: hidden;
   }

   .preview-image {
      width: 100%;
      height: 100%;
   }

   .delete-btn {
      position: absolute;
      top: 0;
      right: 0;
      width: 40rpx;
      height: 40rpx;
      background-color: rgba(0, 0, 0, 0.5);
      border-radius: 0 0 0 8rpx;
      display: flex;
      align-items: center;
      justify-content: center;
   }

   .delete-btn .iconfont {
      color: #fff;
      font-size: 24rpx;
   }

   .upload-btn {
      width: 200rpx;
      height: 200rpx;
      border: 2rpx dashed #ddd;
      border-radius: 8rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #999;
   }

   .upload-btn .iconfont {
      font-size: 60rpx;
      margin-bottom: 10rpx;
   }

   .upload-text {
      font-size: 28rpx;
   }

   .upload-tip {
      font-size: 24rpx;
      color: #999;
      margin-top: 10rpx;
   }
</style>